package com.petvc.tv

import android.annotation.SuppressLint
import android.net.Uri
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Logout
import androidx.compose.material.icons.filled.Logout
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import androidx.core.net.toUri
import androidx.compose.material3.ExperimentalMaterial3Api
import com.petvc.tv.HeartbeatManager

@SuppressLint("UseKtx")
@Composable
fun PlayerScreen() {
    val context = LocalContext.current
    
    // 检查登录状态
    LaunchedEffect(Unit) {
        LogUtils.logDebug("PlayerScreen: 检查登录状态")
        if (!AuthService.isLoggedIn(context)) {
            LogUtils.logDebug("PlayerScreen: 用户未登录，跳转到登录页面")
            // 如果未登录，返回登录页面
            val intent = android.content.Intent(context, LoginActivity::class.java)
            context.startActivity(intent)
            (context as? androidx.activity.ComponentActivity)?.finish()
        } else {
            LogUtils.logDebug("PlayerScreen: 用户已登录，显示播放器界面")
            // 启动Socket连接
            LogUtils.logDebug("PlayerScreen: 启动Socket连接")
            HeartbeatManager.connectAndRegisterDevice(context)
        }
    }
    
    // 状态
    var isPlaying by remember { mutableStateOf(false) }
    var isMuted by remember { mutableStateOf(false) }
    var isLiked by remember { mutableStateOf(false) }
    var isSubscribed by remember { mutableStateOf(false) }
    var showMore by remember { mutableStateOf(false) }
    var progress by remember { mutableStateOf(0.0f) }
    val totalSeconds = 330
    val currentSeconds = (progress * totalSeconds).toInt()
    val minutes = currentSeconds / 60
    val seconds = currentSeconds % 60
    val timestamp = String.format("%02d:%02d / 05:30", minutes, seconds)

    Row(Modifier.fillMaxSize().background(Color(0xFF0F0F0F))) {
        // 主体区域
        Column(Modifier.weight(1f)) {
            // 顶部导航栏 - 优化版本
            @OptIn(ExperimentalMaterial3Api::class)
            TopAppBar(
                title = {
                    Text(
                        text = "PetTV",
                        color = Color.White,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold
                    )
                },
                navigationIcon = {
                    // 可以放置返回按钮或其他导航功能
                    // 暂时留空，保持布局平衡
                },
                actions = {
                    // 用户信息卡片
                    val currentUser = AuthService.getCurrentUser(context)
                    currentUser?.let { user ->
                        Box(
                            modifier = Modifier
                                .padding(end = 8.dp)
                                .background(
                                    color = Color.White.copy(alpha = 0.1f),
                                    shape = RoundedCornerShape(20.dp)
                                )
                                .padding(horizontal = 12.dp, vertical = 6.dp)
                                .clickable {
                                    // 显示用户菜单或直接退出登录
                                    AuthService.logout(context)
                                    val intent = android.content.Intent(context, LoginActivity::class.java)
                                    context.startActivity(intent)
                                    (context as? androidx.activity.ComponentActivity)?.finish()
                                }
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(6.dp)
                            ) {
                                Icon(
                                    androidx.compose.material.icons.Icons.Filled.Person,
                                    contentDescription = null,
                                    tint = Color.White,
                                    modifier = Modifier.size(16.dp)
                                )
                                Text(
                                    text = user.username,
                                    color = Color.White,
                                    fontSize = 12.sp,
                                    fontWeight = FontWeight.Medium
                                )
                                Icon(
                                    Icons.AutoMirrored.Filled.Logout,
                                    contentDescription = "退出登录",
                                    tint = Color.White.copy(alpha = 0.7f),
                                    modifier = Modifier.size(14.dp)
                                )
                            }
                        }
                    }
                },
                colors = androidx.compose.material3.TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF1A1A1A),
                    navigationIconContentColor = Color.White,
                    titleContentColor = Color.White,
                    actionIconContentColor = Color.White
                ),
                modifier = Modifier
                    .background(Color(0xFF1A1A1A))
                    .padding(horizontal = 8.dp)
            )
            
            // 扩大播放器区域，最大宽度1440dp，居中，16:9比例
            Box(
                Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
                    .wrapContentWidth(Alignment.CenterHorizontally)
                    .widthIn(max = 1440.dp)
                    .aspectRatio(16f / 9f)
            ) {
                // ExoPlayer集成
                val context = LocalContext.current
                val videoUrl = "http://x.mp4"
                val exoPlayer = remember {
                    LogUtils.logDebug("PlayerScreen: 创建ExoPlayer实例")
                    ExoPlayer.Builder(context).build().apply {
                        setMediaItem(MediaItem.fromUri(videoUrl.toUri()))
                        prepare()
                        playWhenReady = false
                        LogUtils.logDebug("PlayerScreen: ExoPlayer初始化完成，默认不播放")
                    }
                }
                LogUtils.logDebug("PlayerScreen: 设置ExoPlayer到ExoPlayerHolder")
                ExoPlayerHolder.exoPlayer = exoPlayer
                DisposableEffect(Unit) {
                    onDispose {
                        LogUtils.logDebug("PlayerScreen: 清理ExoPlayer实例")
                        ExoPlayerHolder.exoPlayer = null
                        exoPlayer.release()
                    }
                }
                AndroidView(
                    factory = {
                        PlayerView(it).apply {
                            player = exoPlayer
                            useController = true
                            layoutParams = android.view.ViewGroup.LayoutParams(
                                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                                android.view.ViewGroup.LayoutParams.MATCH_PARENT
                            )
                        }
                    },
                    modifier = Modifier.fillMaxSize()
                )
            }
            // 频道与操作
            Column(Modifier.padding(32.dp, 24.dp, 32.dp, 0.dp)) {
                Row(
                    Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Image(
                            painter = painterResource(id = R.drawable.x),
                            contentDescription = null,
                            modifier = Modifier.size(36.dp).clip(CircleShape)
                        )
                        Spacer(Modifier.width(12.dp))
                        Column {
                            Text("萌宠乐园", color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Medium)
                            Text("268K 订阅", color = Color(0xFFB0B0B0), fontSize = 13.sp)
                        }
                        Spacer(Modifier.width(16.dp))
                        Button(
                            onClick = { isSubscribed = !isSubscribed },
                            shape = RoundedCornerShape(4.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = if (isSubscribed) Color(0xFF666666) else Color(0xFFFF6B35)
                            ),
                            contentPadding = PaddingValues(horizontal = 24.dp, vertical = 8.dp)
                        ) {
                            Text(if (isSubscribed) "已订阅" else "订阅", color = Color.White)
                        }
                    }
                    Row {
                        Button(
                            onClick = { isLiked = !isLiked },
                            shape = RoundedCornerShape(4.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = if (isLiked) Color(0xFFFF6B35) else Color(0xFF232323)
                            ),
                            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)
                        ) {
                            Icon(painterResource(R.drawable.ic_thumb_up), contentDescription = null, tint = Color.White)
                            Spacer(Modifier.width(6.dp))
                            Text(if (isLiked) "2.8K+1" else "2.8K", color = Color.White)
                        }
                        Spacer(Modifier.width(12.dp))
                        Button(
                            onClick = { /* 分享 */ },
                            shape = RoundedCornerShape(4.dp),
                            colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF232323)),
                            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)
                        ) {
                            Icon(painterResource(R.drawable.ic_share), contentDescription = null, tint = Color.White)
                            Spacer(Modifier.width(6.dp))
                            Text("分享", color = Color.White)
                        }
                    }
                }
                Spacer(Modifier.height(24.dp))
                // 视频描述
                Box(
                    Modifier
                        .fillMaxWidth()
                        .background(Color(0xFF232323), RoundedCornerShape(16.dp))
                        .padding(24.dp)
                ) {
                    Column {
                        Text(
                            text = "这只可爱的金毛幼犬名叫 Lucky，今年 3 个月大。视频记录了它和玩具玩耍的欢乐时光，特别是它第一次见到小黄鸭时那惊喜的表情真是太萌了！💝\n欢迎大家在评论区分享你家宠物的趣事！记得点赞订阅，我们下期再见~ 🐾",
                            color = Color(0xFFCCCCCC),
                            fontSize = 15.sp,
                            maxLines = if (showMore) Int.MAX_VALUE else 3,
                            overflow = TextOverflow.Ellipsis
                        )
                        TextButton(onClick = { showMore = !showMore }) {
                            Text(if (showMore) "收起" else "显示更多", color = Color(0xFFB0B0B0))
                        }
                    }
                }
            }
        }
        // 侧边推荐栏
        Box(
            Modifier
                .width(360.dp)
                .fillMaxHeight()
                .background(Color(0xFF161616))
        ) {
            Column(Modifier.padding(24.dp)) {
                Row(
                    Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text("推荐内容", color = Color.White, fontSize = 22.sp, fontWeight = FontWeight.Medium)
                    Row {
                        IconButton(onClick = { /* 上 */ }) {
                            Icon(painterResource(R.drawable.ic_chevron_up), contentDescription = null, tint = Color.White)
                        }
                        IconButton(onClick = { /* 下 */ }) {
                            Icon(painterResource(R.drawable.ic_chevron_down), contentDescription = null, tint = Color.White)
                        }
                    }
                }
                Spacer(Modifier.height(24.dp))
                // 推荐内容列表
                RecommendationItem(
                    imageRes = R.drawable.x,
                    avatarRes = R.drawable.x,
                    title = "哈士奇雪地撒欢，这运动量太猛了！",
                    channel = "雪地旅者",
                    views = "8.2K 次观看 · 2 天前"
                )
                Spacer(Modifier.height(16.dp))
                RecommendationItem(
                    imageRes = R.drawable.x,
                    avatarRes = R.drawable.x,
                    title = "蓝猫的午睡时光，怎么能这么优雅？",
                    channel = "喵星人日记",
                    views = "12K 次观看 · 5 天前"
                )
                Spacer(Modifier.height(16.dp))
                RecommendationItem(
                    imageRes = R.drawable.x,
                    avatarRes = R.drawable.x,
                    title = "柯基和蝴蝶的奇妙邂逅",
                    channel = "汪汪探险队",
                    views = "15K 次观看 · 1 周前"
                )
            }
        }
    }
}

@Composable
fun TagChip(text: String) {
    Box(
        Modifier
            .background(Color.White.copy(alpha = 0.1f), RoundedCornerShape(16.dp))
            .padding(horizontal = 12.dp, vertical = 4.dp)
    ) {
        Text(text, color = Color.White, fontSize = 14.sp)
    }
}

@Composable
fun RecommendationItem(
    imageRes: Int,
    avatarRes: Int,
    title: String,
    channel: String,
    views: String
) {
    Column(
        Modifier
            .clip(RoundedCornerShape(16.dp))
            .background(Color(0xFF232323))
            .clickable { }
            .padding(12.dp)
    ) {
        Image(
            painter = painterResource(id = imageRes),
            contentDescription = null,
            modifier = Modifier
                .fillMaxWidth()
                .height(120.dp)
                .clip(RoundedCornerShape(12.dp)),
            contentScale = ContentScale.Crop
        )
        Spacer(Modifier.height(8.dp))
        Row(verticalAlignment = Alignment.CenterVertically) {
            Image(
                painter = painterResource(id = avatarRes),
                contentDescription = null,
                modifier = Modifier.size(36.dp).clip(CircleShape)
            )
            Spacer(Modifier.width(8.dp))
            Column {
                Text(title, color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.Medium, maxLines = 2, overflow = TextOverflow.Ellipsis)
                Text(channel, color = Color(0xFFB0B0B0), fontSize = 13.sp)
                Text(views, color = Color(0xFF888888), fontSize = 13.sp)
            }
        }
    }
}

@Preview(
    name = "横屏预览",
    widthDp = 1920,
    heightDp = 1080,
    showBackground = true
)
@Composable
fun PlayerScreenPreview() {
    PlayerScreen()
} 